package com.yituo.mjworld.mvc.action.user;

import com.alibaba.fastjson.JSONObject;
import com.yituo.mjworld.core.annotation.NoToken;
import com.yituo.mjworld.core.annotation.Rule;
import com.yituo.mjworld.core.web.core.MyHttpRequest;
import com.yituo.mjworld.core.web.core.MyHttpResponse;
import com.yituo.mjworld.core.web.core.Result;
import com.yituo.mjworld.mvc.entity.UserData;
import com.yituo.mjworld.mvc.entity.web.WxCache;
import com.yituo.mjworld.mvc.entity.web.WxUserinfo;
import com.yituo.mjworld.mvc.service.impl.UserServiceImpl;
import com.yituo.mjworld.mvc.service.impl.WxServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class WxAction {
  @Autowired
  UserServiceImpl userService;
  @Autowired
  WxServiceImpl wxService;

  /**
   * 查看缓存池中的微信关于 ticket 和 token缓存数据
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @NoToken
  public void seeWxCache(MyHttpRequest req, MyHttpResponse res) throws IOException {
    List<WxCache> list = new ArrayList<WxCache>();
    Map<String, WxCache> map = UserData.getWxCacheMap();
    for (String key : map.keySet()) {
      list.add(map.get(key));
    }
    res.success(list);
  }

  //  jsapi_ticket=HoagFKDcsGMVCIY2vOjf9sqancGEtUaRNEWRx91PIn6WyDIqK5wd-cYPcpo2kBhY6z4
//  VCT5S0_CEH3MmjMlmCg&noncestr=2fbf7180803a49f4&timestamp=1514948456906&url=http:/
//      /imopei.95by.cn

  /**
   * 获取微信的JS配置.
   * 该接口仅微信用户可访问.
   * 该接口需本站的仓库管理员访问.非本站的仓库管理员无法访问该接口!
   */
  @NoToken
  @Rule(name = "uid", name_zn = "用户ID")
  public void getWxJsConfig(MyHttpRequest req, MyHttpResponse res) throws IOException {
    String currentUrl = req.getParameter("currentUrl");
    if (StringUtils.isEmpty(currentUrl)) {
      res.failed("未检测到url!");
      return;
    }
    JSONObject config = null;
    String userId = req.getParameter("uid");
    WxUserinfo wxUserinfo = userService.getWxUserInfo(userId);
    if (wxUserinfo == null) {
      res.failed("用户尚未绑定微信信息,无法调用此接口!");
      return;
    }
    WxCache wxCache = UserData.getWxCacheMap().get(wxUserinfo.getOpenid());
    int i = 0;
    do {
      i = i + 1;
      if (wxCache != null) {
        if (wxCache.getTokenCreateTime().getTime() + 7200 * 1000 < System.currentTimeMillis()) {
          if (wxCache.getTicketCreateTime().getTime() + 7200 * 1000 < System.currentTimeMillis()) {
            // 不需要刷新token
            break;
          }
        }
      }
      // 强制刷新token,token 获取失败,返回失败的结果集
      Result result = wxService.refreshTokenAndTicket(wxUserinfo.getOpenid());
      wxCache = UserData.getWxCacheMap().get(wxUserinfo.getOpenid());
      if (!result.getResult()) {
        res.setResult(result);
        return;
      }
    } while (i < 1);
    // 获取wx 调用的 config 对象
    config = wxService.getWxConfig(wxCache.getTicket(), currentUrl);
    res.success(config);
  }
}
